import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {login} from "../request.js";
import {config} from "@/y-ui/utils/fetch.js";
import {loading} from "../global.js";

const LOGIN_KEY = 'LOGIN_KEY',
	INFO_KEY = "INFO_KEY";
const store = new Vuex.Store({
	state: {
		token: '',
		loginStatus: false, //登录状态  控制  token  是否真实登录
		userInfo: false,
		userId: '',
		operating: false, //可编辑控制
		spaceId: '',
		//首页配置 持久到内存
	},
	mutations: {
		LOGIN(state, {
			token
		} = {}) {
			state.token = token || sessionStorage[LOGIN_KEY] || '';
			sessionStorage[LOGIN_KEY] = state.token;
			state.loginStatus = !!state.token;
			config.headers["X-Access-Token"] = state.token;
		},
		//保存用户信息
		SAVEUSER(state, userInfo = false) {
			state.userInfo = userInfo || uni.getStorageSync(INFO_KEY) || false;
			const {
				fkDingTalkUserId,
				supervisionDeptId = '',
				dingTalkDept = [],
				spaceId = ''
			} = (state.userInfo || {});
			state.userId = fkDingTalkUserId;
			state.spaceId = spaceId;
			state.operating = (dingTalkDept || []).includes(supervisionDeptId);
			uni.setStorageSync(INFO_KEY, state.userInfo);
		},
		//退出
		LOGOUT(state) {
			state.token = '';
			state.loginStatus = false;
			sessionStorage.removeItem(LOGIN_KEY);
		},
		//退出
		LOGOUTUSER(state) {
			state.userInfo = false;
			uni.removeStorageSync(INFO_KEY);
		},
		//空间ID
		SPACEID(state, id) {
			state.spaceId = id;
		}
	},
	actions: {
		//静默登录
		login({
			commit,
			state
		}, data = {}) {
			commit('LOGIN', data);
			commit("SAVEUSER");
			return new Promise((r, j) => {
				if (!state.token) {
					login().then(res => {
						commit('LOGIN', res);
						commit("SAVEUSER", {
							...(res.userInfo || {})
						});
						r(res);
					}).catch(error => {
						j(error);
					});
				} else {
					r({});
				}
			}).finally(loading({msg:"登录中"}));
		},
		//静默退出
		logout({
			commit
		}, stauts) {
			commit("LOGOUT");
			!stauts && commit('LOGOUTUSER');
			return new Promise(r => {
				r();
			});
		},
		//取得空间ID
		async getSpaceID({
			commit,
			state:{spaceId = ''}
		}){
			if(spaceId){
				return spaceId;
			}
			const res = await getCustomSpace();
			commit('SPACEID',res.result);
		}
	}
})

export default store
